<template>
	<view class="apply-for-store">
		<view class="container">
			<uni-forms ref="baseForm" :modelValue="baseFormData" :rules="rules">
			    <view class="top-forms">
				    <view class="info-title">商家信息</view>
					<!-- <uni-forms-item class="forms-box-s" name="store_name">
						<view class="details-box">
							<view class="label-">店铺名称</view><view class="right-value"><input v-model="baseFormData.store_name" class="uni-input-info-shopName" :focus="false" placeholder="请输入店铺名称" /></view>
						</view>
					</uni-forms-item>
					<uni-forms-item class="forms-box-s" name="legal_person">
						<view class="details-box">
							<view class="label-">姓名</view><view class="right-value"><input v-model="baseFormData.legal_person" class="uni-input-info-shopName" :focus="false" placeholder="请输入姓名" /></view>
						</view>
					</uni-forms-item>
					<uni-forms-item class="forms-box-s" name="tel">
						<view class="details-box">
							<view class="label-">电话</view><view class="right-value"><input v-model="baseFormData.tel" class="uni-input-info-shopName" :focus="false" placeholder="请输入联系电话" /></view>
						</view>
					</uni-forms-item> -->
					<uni-forms-item class="forms-box-s" name="address">
						<view class="details-box">
							<view class="label-">所在地区</view>
							<view class="right-value">
								<uni-data-picker placeholder="请选择地址" v-slot:default="{data, error, options}" popup-title="请选择地址" :localdata="dataTree" v-model="baseFormData.address" @change="onchange">
									<view v-if="error" class="error">
										<text>{{error}}</text>
									</view>
									<view v-else-if="data.length" class="selected">
										<view v-for="(item,index) in data" :key="index" class="selected-item">
										   <text>{{item.text}} <text v-if="index !== data.length - 1">/</text></text>
										</view>
									</view>
									<view v-else class="addr-default-tips">
										<text>请选择省/市/区</text>
										<uni-icons type="right" size="20"></uni-icons>
									</view>
								</uni-data-picker>
							</view>
						</view>
					</uni-forms-item>
					<!-- <uni-forms-item class="forms-box-s" name="full_address">
						<view class="details-box">
							<view class="label-">详细地址</view><view class="right-value"><input v-model="baseFormData.full_address" class="uni-input-info-shopName" :focus="false" placeholder="请输入详细地址" /></view>
						</view>
					</uni-forms-item> -->
				<!-- 	<uni-forms-item class="forms-box-s">
						<view class="details-box">
							<view class="label-">行业分类</view>
							<view class="right-value"> -->
								<!-- <uni-data-checkbox multiple :map="mapObj" v-model="baseFormData.industry_category" @change="onchange2" :localdata="categoryList"></uni-data-checkbox> -->
						<!-- 	</view>
						</view>
					</uni-forms-item> -->
				<!-- 	<uni-forms-item class="forms-box-s">
						<view class="details-box">
							<view class="label-">营业时间</view>
							<view class="right-value">
								<picker mode="multiSelector" :range="multiRange" @change="onChange5" :value="baseFormData.business_hours">
								  <view class="addr-default-tips">
								  	<text>{{multiIndex[0]}} - {{multiIndex[1]}}</text>
								  	<uni-icons type="right" size="20"></uni-icons>
								  </view>
								</picker>
							</view>
						</view>
					</uni-forms-item> -->
			    </view>
				<!-- <view class="top-forms">
				    <view class="info-title">商家图片</view>
					<uni-forms-item class="forms-box-s">
						<view class="logo-boxss">
							<view class="label-logo">商家LOGO</view>
							<view class="logo-tips">
								<view>1.图片分辨率不超过200*200</view>
								<view>2.大小不超过1M</view>
							</view>
							<view class="right-value">
								<uni-file-picker 
									v-model="baseFormData.logo"
									@select="select($event, 'logo', 0)" 
									@delete="onDelete($event, 'logo')"
									:auto-upload="false"
									@progress="progress" 
									:limit="1"
									@success="success" 
									@fail="fail"
									file-mediatype="image">
									<view class="upload-img">
										<uni-icons custom-prefix="iconfont" type="icon-xiangji2" size="30"></uni-icons>
									</view>
								</uni-file-picker>
							</view>
						</view>
					</uni-forms-item>
				</view> -->
				<view class="top-forms">
					<uni-forms-item class="forms-box-s" name="introduce">
						<view class="logo-boxss">
							<view class="label-logo">商家介绍</view>
							<view class="right-value" style="margin-top: 20rpx">
								<uni-easyinput type="textarea" autoHeight v-model="baseFormData.introduce" placeholder="请输入商家介绍,内容越详细,越能吸引更多用户"></uni-easyinput>
							</view>
						</view>
					</uni-forms-item>
				</view>
			    <button type="primary" class="submit-btn" @click="submit('baseForm')">申请商家</button>
			</uni-forms>
			<!-- 提示信息弹窗 -->
			<uni-popup ref="message" type="message">
				<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
			</uni-popup>
		</view>
	</view>
</template>

<script>
	import * as UserApi from '@/api/user'
	export default {
		data() {
			return {
				baseFormData: {
					// store_name: '', // 店铺名称
					// legal_person: '', //  姓名
					// tel: '', // 电话
					address: '', // 地址
					// full_address: '', // 详细地址
					// industry_category: '', // 行业分类
					// business_hours: '00:00 - 24:00', //营业时间
					// section_business: '', //分段营业
					// status: '' , // 招聘状态
					logo: [], // 店铺logo
					// banner: [], // 店铺幻灯片
					// photo: [], // diaper照片
					introduce: '', // 店铺介绍
					// certification: [], // 营业执照
				},
				// 省市区
				dataTree: [],
				categoryList: [],
				multiRange: [], // 存储多列数据
			    multiIndex: ['00:00', '24: 00'], // 存储选中的多列索引
				businessList: [{
					text: "分段营业",
					value: "1",
				}],
				statusList:[{
					text: "正常",
					value: "1",
				}], // 招聘状态
				rules: {
					// 对store_name字段进行必填验证
					// store_name: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入店铺名称',
					// 	}]
					// },
					// legal_person: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入姓名',
					// 	}]
					// },
					// // 对email字段进行必填验证
					// email: {
					// 	rules: [{
					// 		format: 'email',
					// 		errorMessage: '请输入正确的邮箱地址',
					// 	}]
					// },
					// tel: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '手机号码不能为空'
					// 	},{
					// 		pattern: /^1[3456789]\d{9}$/,
					// 		errorMessage: '手机号码不正确'
					// 	}]
					// },
				},
				msgType: 'success',
				messageText: '提交成功',
				region: [], // 获取所在地区地址数组
				logo_image_id: '', // logo
				certificationIds: [], // 营业执照
				bannerIds: [], // 店铺幻灯片
				photoIds: [], // 照片
				mapObj:{
					text:'name',
					value:'store_classify_id'
				}
			}
		},
		onLoad() {
		    this.initMultiPicker(); // 时分
			this.get_region_tree() // 获取地区树状结构 
			// this.get_classifyList() // 行业分类列表
		},
		methods: {
			/*
			    获取地区树状结构 
			*/
			get_region_tree() {
				const app =this
				UserApi.regionTree({ }, { load: false })
				  .then(result => {
				    // 合并新数据
					let array = []
					for(var i in result.data.list) {
						array.push(result.data.list[i]) 
					}
					console.log(result.data, app.replaceValueInTree(array))
					this.dataTree = app.replaceValueInTree(array)
				  })
			},
			// item内的值根据实际情况更换
			replaceValueInTree (tree) {
			　　const result = []
			　　tree.forEach((item) => {
			　　　　let obj = item.city || item.region || {}
			      let children = Object.values(obj)
			　　　　if (Array.isArray(children) && children.length > 0) {
			　　　　　　children = this.replaceValueInTree(children)
			　　　　}
					if(item.level == 3) {
						var newItem = {
							id: item.id,
							level: item.level,
							text: item.name,
							value: item.id,
							pid: item.pid
				　　　　}
					} else {
						newItem = {
							id: item.id,
							level: item.level,
							text: item.name,
							value: item.id,
							pid: item.pid,
				　　　　　 　children: children
				　　　　}
					}
			　　　　result.push(newItem);
			　　})
			　　return result
			},
			// 行业分类列表
			get_classifyList: function() {
				classifyList().then(res => {
					console.log('333', res)
					if(res.status == 200) {
						this.categoryList = res.data.list
					}
				}).catch(err => {
				})
			},
			// 提交
			submit(ref) {
				let that = this
				this.$refs[ref].validate().then(res => {	
					let obj = {
						"form": {
							// that.logo_image_id
							 "image" :"", //图片地址
							 "content":res.introduce, //申请内容
							 "region_id":that.region
						}
					}
					console.log('success', res, obj);
					UserApi.getMerchantApply(obj, { load: false }).then(result => {
						// 合并新数据
						console.log(result)
						uni.showToast({
							title: '提交成功'
						})
						setTimeout(() => {
							uni.reLaunch({
								url:'/pages/user/index'
							})
						},2000)
					}).catch(er => {
						
					})
				}).catch(err => {
					console.log('err', err);
					that.msgType = 'error'
					that.messageText = err[0].errorMessage
					that.$refs.message.open()
				})
			},
			// 省市区
			onchange(e) {
				let arr = JSON.stringify(e.detail.value)
				// this.handleDealFilter(JSON.parse(arr),'name','text')
				this.region = JSON.parse(arr).map((item) => item.value)
				console.log('onchange:',arr, e, this.region);
			},
			/**
			* 替换字段
			*/
			handleDealFilter(arr, key, replaceKey) {
			  let newArr = [];
			  arr.forEach((item, index) => {
			    for (var i = 0; i < key.length; i++) {
				 item[key] = item[replaceKey];
			    }
				delete item[replaceKey]
			    newArr.push(item);
			  });
			  return newArr;
			},
			// 行业分类
			onchange2(e) {
				console.log(e, this.baseFormData.industry_category)
			},
			// 分段营业
			onchange3(e) {
				
			},
			// 招聘状态
			onchange4(e) {
				
			},
			// 营业时间
			onChange5(e){
				let data = e.detail.value
				data = data.map(item => {
					if(item < 10) {
						return '0' + item
					} else {
						return item
					}
				})
				this.multiIndex = [data[0] +':'+ data[1], data[2] +':'+ data[3]];
				this.baseFormData.business_hours = this.multiIndex.join('-')
				console.log(e,data, this.baseFormData.business_hours)
			},
			initMultiPicker() {
			      const hours = [];
			      for (let i = 0; i < 24; i++) {
					if(i < 10) i = '0' + i
			        hours.push(i + '时');
			      }
			 
			      const minutes = [];
			      for (let i = 0; i < 60; i++) {
					if(i < 10) i = '0' + i
			        minutes.push(i + '分');
			      }
			 
				 const hours2 = [];
				 for (let i = 0; i < 24; i++) {
					if(i < 10) i = '0' + i
				   hours2.push(i + '时');
				 }
							 
				 const minutes2 = [];
				 for (let i = 0; i < 60; i++) {
				   if(i < 10) i = '0' + i
				   minutes2.push(i + '分');
				 }
			      this.multiRange = [hours, minutes, hours2, minutes2];
			},
			// 获取上传状态
			select(e, type, groupId){
				console.log('选择文件：',e, type)
				
				// 执行异步和同步代码
				// uni.uploadFile({
				// 	url: config.baseUrl + "/upload/image",
				// 	name: "iFile",
				// 	filePath: e.tempFilePaths[0],
				// 	// file: e.tempFiles[0].file,
				// 	formData: { groupId: groupId },
				// 	header: {
				// 		// 'Content-Type': 'multipart/form-data',
				// 		"token": uni.getStorageSync('Token')
				// 	},
				// 	success: (res) => {
				// 		const urlData = JSON.parse(res.data)
				// 		if(urlData.status == 200) {
				// 			// toast(urlData.message)
				// 			uni.showToast({
				// 			  icon: 'success',
				// 			  title: urlData.message
				// 			})
				// 			// 状态码为200,说明上传成功了
				// 			let str = urlData.data.fileInfo.external_url
				// 			var indexs = str.lastIndexOf("/")
				// 			var resolves = str.substring(indexs + 1, str.length);
				// 			if(type=='logo') {
				// 				// this.baseFormData.logo.push(urlData.data.fileInfo.external_url)
				// 				this.logo_image_id = urlData.data.fileInfo.file_id
				// 				this.baseFormData.logo.push({url:urlData.data.fileInfo.external_url,name:resolves})
				// 			}
							// if(type=='certification'){
							// 	this.baseFormData.certification.push({url:urlData.data.fileInfo.external_url,name:resolves})
							// 	this.certificationIds.push(urlData.data.fileInfo.file_id)
							// }
							// if(type=='banner'){
							// 	this.baseFormData.banner.push({url:urlData.data.fileInfo.external_url,name:resolves})
							// 	this.bannerIds.push(urlData.data.fileInfo.file_id)
							// }
							// if(type=='photo'){
							// 	this.baseFormData.photo.push({url:urlData.data.fileInfo.external_url,name:resolves})
							// 	this.photoIds.push(urlData.data.fileInfo.file_id)
							// }
					// 	}
					// 	console.log(urlData, res, this.logo_image_id)
					// },
					// fail: (error) => {
					// 	console.log(error)
					// 	// toast(error.message)
					// },
				// })
			},
			onDelete(e, type) {
				// 当文件删除时触发
				console.log('ewerwerew',e)
				if(type=='logo') {
					const num = this.baseFormData.logo.findIndex(v => v.url === e.tempFilePath);
					this.baseFormData.logo.splice(num, 1);
					this.logo_image_id = ''
				}
				// if(type=='certification'){
				// 	const num = this.baseFormData.certification.findIndex(v => v.url === e.tempFilePath);
				// 	this.baseFormData.certification.splice(num, 1)
				// 	this.certificationIds.splice(e.index, 1)
				// }
				// if(type=='banner'){
				// 	const num = this.baseFormData.banner.findIndex(v => v.url === e.tempFilePath);
				// 	this.baseFormData.banner.splice(num, 1)
				// 	this.bannerIds.splice(e.index, 1)
				// }
				// if(type=='photo'){
				// 	const num = this.baseFormData.photo.findIndex(v => v.url === e.tempFilePath);
				// 	this.baseFormData.photo.splice(num, 1)
				// 	this.photoIds.splice(e.index, 1)
				// }
			},
			// 获取上传进度
			progress(e){
				console.log('上传进度：',e)
			},
			
			// 上传成功
			success(e){
				console.log('上传成功', e)
			},
			
			// 上传失败
			fail(e){
				console.log('上传失败：',e)
			}
		}
	}
</script>

<style scoped>
	.top-forms{
		background-color: #fff;
		padding: 29rpx 32rpx 0 32rpx;
		border-radius: 14rpx;
		margin-bottom: 24rpx
	}
	.info-title{
		font-family: MicrosoftYaHei;
		font-size: 32rpx;
		color: #161616;
		margin-bottom: 15rpx;
		font-weight: 600;
	}
	.forms-box-s{
		margin-bottom: 0;
	}
	.details-box{
		display: flex;
		justify-content: space-between;
		align-items: center;
		line-height: 75rpx;
		border-bottom: 2rpx solid #F4F4F4;
		padding: 20rpx 0;
	}
	.label-{
		color: #161616;
		flex: 1;
		margin-right: 46rpx;
		text-align-last: justify;
		font-weight: 600;
	}
	.right-value{
		font-family: MicrosoftYaHei;
		color: #A8A8A8;
		flex:4;
	}
	.addr-default-tips{
		display: flex;
		justify-content: space-between;
		color: #262626;
	}
	.selected{
		display: flex;
		flex-wrap: wrap;
	}
	.selected-item{
		color: #262626;
	}
	.submit-btn{
		/* background: #41C8F7; */
		background: #fa2209;
		border-radius: 46rpx;
		margin: 29rpx 32rpx 20rpx 32rpx;
	}
	.logo-boxss{
		padding: 20rpx 0;
	}
	.label-logo{
		color: #161616;
		font-weight: 600;
	}
	.logo-tips{
		color: #999999;
		margin: 15rpx 0;
	}
	.upload-img{
		width: 200rpx;
		height: 200rpx;
		background: #FAFAFA;
		border-radius: 14rpx;
		border: 1rpx dashed #C2C2C2;
		text-align: center;
		line-height: 200rpx;
	}
	.upload-details{
		line-height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		color: #333333;
	}
	.d-tips{
		color: #CCCCCC;
	}
</style>